package com.mjh.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.util.concurrent.TimeUnit;

/**
 * 验证码接口
 *
 * @author MJH
 * @date 2021-12-03
 * @Description 验证码接口
 */
@RestController
public class CaptchaController {



    @Autowired
    private HttpServletRequest request;


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 图形验证码接口
     * @return  image/base64
     */
    @GetMapping("/captcha")
    public String getCaptcha(HttpServletResponse response){

        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(300, 100, 5, 3);
        captcha.setBackground(new Color(255,255,255));
        String imageBase64 = captcha.getImageBase64();
        //生成验证码key  避免在多线程情况下生成同一key
        String captchaKey =null;
        synchronized (this){
            captchaKey = DigestUtil.md5Hex(System.currentTimeMillis() + "");
        }
        response.setHeader("code",captchaKey);
        //设置验证码
        redisTemplate.opsForValue().set(captchaKey,captcha.getCode(),3, TimeUnit.MINUTES);

        return "data:image/jpg;base64,"+imageBase64;
    }

}
